package com.xianan.xuhui.netsecurityproject.utils;

import com.alibaba.fastjson.JSON;
import com.xianan.xuhui.netsecurityproject.domain.token.WebSessionDto;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaoli
 * @description 用户前端token工具类
 * @since 2025/3/25 9:55
 */
@Component
public class WebTokenUtil {
    private static String WEB_TOKEN_REDIS_KEY = "NET:SECURITY:WEB:TOKEN:KEY:";

    private static long EXPIR_TIME = 2 * 60 * 60;

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    public String createToken(WebSessionDto webSessionDto) {
        String token = getUUID();
        webSessionDto.setToken(token);
        setToken(webSessionDto, token);
        return token;
    }
    public void setToken(WebSessionDto webSessionDto, String token) {

        redisTemplate.boundValueOps(generateKey(token)).set(JSON.toJSONString(webSessionDto), EXPIR_TIME, TimeUnit.SECONDS);
    }
    public void refreshToken(WebSessionDto webSessionDto, String token) {
        redisTemplate.boundValueOps(generateKey(token)).set(JSON.toJSONString(webSessionDto), EXPIR_TIME, TimeUnit.SECONDS);
    }
    public void refreshFullToken(WebSessionDto webSessionDto, String token) {
        redisTemplate.boundValueOps(token).set(JSON.toJSONString(webSessionDto), EXPIR_TIME, TimeUnit.SECONDS);
    }
    public void clearToken(String token) {
        deleteToken(token);
    }

    public boolean verifyToken(String token) {
        boolean result = false;
        if (null!= getToken(token)) {
            result = expirTime(token);
        }
        return result;
    }

    public WebSessionDto getTokenUser(String token) {
        return getToken(token);
    }

    private WebSessionDto getToken(String token) {
        String res = (String) redisTemplate.boundValueOps(generateKey(token)).get();
        if(null ==res){
            return null;
        }
        return JSON.parseObject(res,WebSessionDto.class);
    }

    private boolean expirTime(String token) {
        return redisTemplate.boundValueOps(generateKey(token)).expire(EXPIR_TIME, TimeUnit.SECONDS);
    }



    private void deleteToken(String token) {
        redisTemplate.delete(generateKey(token));
    }


    /**
     * 生成token
     * @param token
     * @return token
     */
    public String generateKey(String token) {
        return WEB_TOKEN_REDIS_KEY + token;
    }


    public static String getUUID() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replaceAll("-", "");
    }
}
